# koroFileHeader at Yungoal acer
# Create: 2023-10-18 16:39:19
# LastEdit: 2023-10-20 15:29:09
"""创建超级用户
https://docs.djangoproject.com/zh-hans/4.1/ref/contrib/auth/#manager-methods
https://docs.djangoproject.com/zh-hans/4.1/topics/auth/default/#topics-auth-creating-users
"""
__author__ = '749B'
# pylint: disable=import-error, missing-function-docstring

if __name__ == '__main__':
    # 导入路径
    from pathlib import Path
    BASE_DIR = Path(__file__).resolve().parent.parent
    import sys
    sys.path.append(str(BASE_DIR))
    # Django 初始化
    import django
    from django.conf import settings
    from ygcmp import settings as my_settings
    settings.configure(**{ k: v for k, v in vars(my_settings).items() if k.isupper() })
    django.setup()


# pylint: disable=wrong-import-position
import configparser

# pylint: disable=ungrouped-imports
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.utils import dateparse

from apps.resourcemanager import models

from secret import db_init


def make_migrations():
    call_command("makemigrations")

def migrate():
    call_command("migrate")

def create_superuser():
    # 正确引用User模型，不要直接导入 from django.contrib.auth.models import User
    # https://docs.djangoproject.com/zh-hans/4.2/topics/auth/customizing/#referencing-the-user-model
    # pylint: disable-next=invalid-name
    User = get_user_model()
    try:
        User.objects.get(username=db_init.SUPERUSER['username'])
    except User.DoesNotExist:
        user = User.objects.create_superuser(**db_init.SUPERUSER)
        user.save()

def add_accounts():
    config = configparser.ConfigParser()
    config.read('secret/credentials_dev.ini', encoding='utf-8')
    cred_list = [ config[sec] for sec in config.sections() ]
    for cred in cred_list:
        customer, _ = models.Customer.objects.update_or_create(
            name=cred['customer'],
            )
        account, _ = models.Account.objects.update_or_create(
            name=cred['account'],
            defaults={'customer': customer} | \
                {k: v for k, v in cred.items() if k in ['account_alias', 'account_id']},
            )
        created_at = dateparse.parse_datetime(
            cred.get('created_at', '').replace('年', '-').replace('月', '-').replace('日', '')
            ).astimezone()
        models.User.objects.update_or_create(
            name=cred['user'],
            defaults={'account': account, 'created_at': created_at} | \
                {k: v for k, v in cred.items() if k in ['access_key_id', 'access_key_secret']}
            )


def main():
    call_command("makemigrations")
    call_command("migrate")
    create_superuser()
    add_accounts()

if __name__ == '__main__':
    main()
